<template>
  <ElCard  v-loading="loadingTable">
    <div class="flex justify-start">
      <el-button class="mr-2" type="primary" @click="returnPage">返回</el-button>
      <el-button class="mr-2" type="primary" @click="updateProductionPlan(0)">保存</el-button>
    </div>
    <div class="production-scheduling" >
        <el-form :inline="true"  :model="productionPlan" :rules="rules" class="flex flex-wrap justify-start " label-width="100px" style="align-items: center;">
          <el-form-item label="排产编号:">
            <el-input v-model="productionPlan.productionPlanCode" disabled></el-input>
          </el-form-item>
          <el-form-item label="总计划数量:">
            <el-input-number v-model="productionPlan.planQuantity" disabled :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="备注:">
          <el-input v-model="productionPlan.remark" type="textarea" :rows="1"/>
          </el-form-item>
        </el-form>

      <el-table :data="materialList" border style="width: 100%; margin-top: 20px">
        <el-table-column prop="materialCode" label="物料编码" align="center" width="220"></el-table-column>
        <el-table-column prop="materialName" label="物料名称" align="center" width="220"></el-table-column>
        <el-table-column prop="orderQuantity" label="计划数量" align="center" width="100"></el-table-column>
        <el-table-column prop="schedulingQuantity" label="排产数量" align="center" width="100">
          <template #default="scope">
            {{scope.row.schedulingQuantity}}
          </template>
        </el-table-column>
        <el-table-column label="生产车间" width="160" align="center">
          <template #header>
            <div class="flex justify-center items-center">
              <div style="color: #FF3030;">&nbsp*&nbsp</div>
              <div>生产车间</div>
            </div>
          </template>
          <template #default="scope">
            <el-select v-model="scope.row.workshop" placeholder="请选择车间">
              <el-option
                v-for="(item, index) in gridList"
                :key="index"
                :label="item.gname"
                :value="item.gid"
              />
            </el-select>
          </template>
        </el-table-column>

        <!-- 动态生成日期列 -->
        <el-table-column
          v-for="(planTime, index) in formattedPlanTimes"
          :key="index"
          :prop="planTime"
          :label="planTime"
          width="160"
          align="center"
        >
          <template #default="scope">
            <el-input-number
              v-model="scope.row.scheduleQuantities[planTime]"
              :min="0"
              @change="inputScheduling(scope.row,index)"
              style="width:130px"
              placeholder=""
              class="quantity-input"
            ></el-input-number>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ $index }">
            <Button
              type="link"
              style="color: red"
              @click="deleteRow($index)"
            >
              删除
            </Button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="orderDialogVisible" title="选择销售订单" @close="dialogCancel_btn" width="80%" >
        <div class="dialog-head" style="display: flex;"  >
          <el-form :inline="true" :model="dialogFormData">
            <el-form-item label="销售订单号">
              <el-input v-model="dialogFormData.relatedOrderNumber" clearable
                        placeholder="请输入销售订单号"></el-input>
            </el-form-item>
            <el-form-item label="物料名称">
              <el-input v-model="dialogFormData.materialName" clearable
                        placeholder="请输入物料名称"></el-input>
            </el-form-item>
            <el-form-item label="物料编码">
              <el-input v-model="dialogFormData.materialCode" clearable
                        placeholder="请输入物料编码"></el-input>
            </el-form-item>
            <el-form-item label="客户名称">
              <el-input v-model="dialogFormData.customerName" clearable
                        placeholder="请输入客户名称"></el-input>
            </el-form-item>
            <el-form-item label="客户编码">
              <el-input v-model="dialogFormData.customerCode" clearable
                        placeholder="请输入客户编码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search_btn">
                搜索
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="orderList" v-loading="loadingDialog" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="saleOrderNumber" label="销售订单号"></el-table-column>
          <el-table-column prop="materialCode" label="物料编码"></el-table-column>
          <el-table-column prop="materialName" label="物料名称"></el-table-column>
          <!--          <el-table-column prop="standard" label="物料规格"></el-table-column>-->
          <el-table-column prop="quantity" label="数量"></el-table-column>
          <el-table-column prop="customerName" label="客户名称"></el-table-column>
          <el-table-column prop="customerCode" label="客户编码"></el-table-column>
          <el-table-column prop="personal" label="销售员"></el-table-column>
        </el-table>
        <div class="block" style="display: flex; justify-content: flex-end">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="sizeChangeEvent"
            @current-change="currentChangeEvent"
          ></el-pagination>
        </div>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmOrderSelection">确定</el-button>
        </span>
        </template>
      </el-dialog>
    </div>
  </ElCard>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import {
  ElCard,
  ElDatePicker,
  ElPagination,
  ElMessage,
  ElTable,
  ElTableColumn,
  ElInput,
  ElInputNumber,
  ElButton,
  ElFormItem,
  ElLoading,
  ElRadio,
  ElRadioGroup,
  ElOption,
  ElForm,
  ElDialog,
  ElSelect,
  ElRadioButton
} from "element-plus";
import { Button } from "ant-design-vue";
import {getGridApi,getProductionPlanDetailApi,getSaleOrderApi,updateProductionPlanApi} from "#/api/productionPlan/index.js";
import { useRoute, useRouter } from "vue-router";
const rules = reactive(
 {
  // 添加 planTime 的验证规则
  planTime: [
    {
      required: true,
      message: '请选择计划时间',
      trigger: ['blur', 'change']
    }
  ],
   workshop: [
     {
       required: true,
       message: '请选择计划时间',
       trigger: ['blur', 'change']
     }
   ],
  // 其他字段的验证规则可以在这里添加
})
// 排产类型（周/月）
const schedulingType = ref('week');
const planId = ref(null); // 计划ID
const orderDialogVisible = ref(false);
const selectedOrders = ref([]);
// 销售订单列表
const orderList = ref([]);
const dialogFormData = ref({});

//销售弹窗
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 物料列表
const materialList = ref([]);
const productionPlan = ref({
  remark:'',
  planTime:'',
});

const gridList = ref([]);
// 日期列（动态生成）
const formattedPlanTimes = ref([]); // 格式化后的计划时间列表
const router = useRouter();
const route = useRoute();
const loadingTable = ref(true)
const loadingDialog = ref(true)

// 返回事件
const returnPage = () => {
  router.push({name:"productionPlanList"}); // 返回列表页
};
//销售订单对应的物料
const saleAndMaterialList = ref([]);
// 切换排产周期
const changeSchedulingType = () => {
  generateDateColumns();
};

// 生成日期列
const generateDateColumns = () => {
  const today = new Date();
  const columns = [];
  if (schedulingType.value === "week") {
    const today = new Date(); // 获取当前日期
    const dayOfWeek = today.getDay(); // 获取今天是星期几（0 表示星期日，1 表示星期一，以此类推）

    // 计算下周一的日期
    const nextMonday = new Date(today);
    nextMonday.setDate(today.getDate() + (dayOfWeek === 0 ? 1 : (1 - dayOfWeek + 7) % 7));

    // 生成从下周一到下周五的日期
    for (let i = 0; i < 5; i++) {
      const currentDate = new Date(nextMonday);
      currentDate.setDate(nextMonday.getDate() + i);
      columns.push(currentDate);
    }
  } else {
    const currentYear = today.getFullYear();
    const currentMonth = today.getMonth();
    // 创建一个表示下个月第一天的日期对象
    const nextMonthStart = new Date(currentYear, currentMonth + 1, 1);
    // 创建一个表示下下个月第一天的日期对象（用于获取下个月的最后一天）
    const nextMonthEnd = new Date(currentYear, currentMonth + 2, 0);
    // 获取下个月的天数
    const daysInNextMonth = nextMonthEnd.getDate();
    // 按月生成下个月每一天的日期
    for (let i = 1; i <= daysInNextMonth; i++) {
      const currentDate = new Date(currentYear, currentMonth + 1, i);
      columns.push(currentDate);
    }
  }
  formattedPlanTimes.value = Array.from(columns).map(time => formatDate(new Date(time)));
  //清空之前的数据
  materialList.value.forEach(material => {material.scheduleQuantities={}});
  formattedPlanTimes.value.forEach(date => {
    materialList.value.forEach((num)=>{
      num.scheduleQuantities[date]=0
    });
  })
};

// 打开订单选择弹窗
const openOrderDialog = () => {
  orderDialogVisible.value = true;
  getSaleOrderList();
};

function getSaleOrderList() {
  loadingDialog.value=true;
  const params = Object.fromEntries(
    Object.entries(dialogFormData.value).filter(([key, value]) => value)
  );
  // 使用 params 发起请求
  console.log("params", params); // 此时 params 中不包含值为空的字段
  getSaleOrderApi({ size: pageSize.value, page: currentPage.value, ...params })
    .then((response) => {
      console.log("content", response.data.content);
      orderList.value = response.data.content;
      total.value = response.data.totalElements;
      loadingDialog.value=false;
    })
    .catch((error) => {
      loadingDialog.value=false;
      console.error("获取销售订单列表失败!", error);
    });
}

function dialogCancel_btn() {
  console.log(111111123);
  orderDialogVisible.value = false;
  dialogFormData.value = {};
  currentPage.value = 1;
  pageSize.value = 10;
  total.value = 0;
}

function search_btn() {
  getSaleOrderList();
}

function sizeChangeEvent(val) {
  pageSize.value = val;
  getSaleOrderList();
}

function currentChangeEvent(val) {
  currentPage.value = val;
  getSaleOrderList();
}


// 处理订单选择
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection;
};
// 确认订单选择
const confirmOrderSelection = () => {
  console.log("selectOrder",selectedOrders.value);
  const mergedOrders = mergeOrdersByMaterialCode(selectedOrders.value);
  materialList.value.push(...mergedOrders);
  formattedPlanTimes.value.forEach(date => {
    materialList.value.forEach((num)=>{
      num.scheduleQuantities[date]=0;
    });
  })
  console.log('Merged Orders:', mergedOrders);
  console.log('Sale Order:', selectedOrders.value);
  dialogCancel_btn();
  orderDialogVisible.value = false;
};

// 根据 materialCode 合并 orderQuantity
function mergeOrdersByMaterialCode(orders) {
  const merged = {};
  // 遍历每个订单
  for (const order of orders) {
    const { materialCode, quantity, materialName,saleOrderNumber } = order;
    saleAndMaterialList.value.push({saleCode:saleOrderNumber,materialCode:materialCode});
    // 如果 materialCode 已经存在，则累加 orderQuantity，否则初始化
    if (merged[materialCode]) {
      merged[materialCode].orderQuantity += quantity;
    } else {
      merged[materialCode] = {
        orderQuantity: quantity,
        materialCode,
        materialName,
        scheduleQuantities: {
        } // 初始化 scheduleQuantities 对象
      };
    }
  }
  console.log("saleAndMaterialList",saleAndMaterialList.value);

  // 将对象转换回数组
  return Object.values(merged);
}
//计算排产数量
function inputScheduling(row,index){
  console.log("row",row);
  // row.scheduleQuantities
  // let total=0;
  // for (let key in row.quantities) {
  //   if (row.quantities.hasOwnProperty(key)) {
  //     total += row.quantities[key];
  //   }
  // }
  row.schedulingQuantity = Object.values(row.scheduleQuantities).reduce((sum, current) => sum + current, 0);

  console.log(row.schedulingQuantity);
}
// 获取车间列表
const getGridList = async () => {
  await getGridApi().then((response) => {
    console.log("content", response.data.content);
    gridList.value = response.data.content;
  })
};

// 获取生产计划详情
const getProductionPlanDetail =async () => {
  loadingTable.value=true;
  const id = route.params.id; // 从路由参数获取计划ID
  planId.value = id;
  await getProductionPlanDetailApi({ id:id}).then(response => {
    const detailList = response.data[0].productPlanMaterialList || []; // 确保 detailList 是一个数组
    productionPlan.value=response.data[0];
    // 提取所有唯一的 planTime
    const planTimes = new Set();
    detailList.forEach(detail => {
      console.log("detail",detail);
      (detail?.productPlanMaterialNumberList || []).forEach(item => { // 确保 planMaterialNumberList 是一个数组
        planTimes.add(item.planTime);
      });
    });

    formattedPlanTimes.value = Array.from(planTimes).map(time => formatDate(new Date(time)));
    // 重组物料数据，包含每个 planTime 的 quantity
    materialList.value = detailList.map(detail => {
      const scheduleQuantities = {};
      (detail.productPlanMaterialNumberList || []).forEach(item => { // 确保 planMaterialNumberList 是一个数组
        scheduleQuantities[formatDate(new Date(item.planTime))] = item.quantity;
      });
      return {
        id: detail.id,
        materialCode: detail.materialCode,
        materialName: detail.materialName,
        schedulingQuantity: detail.schedulingQuantity,
        orderQuantity: detail.orderQuantity,
        workshop: detail.gripId,
        scheduleQuantities // 每个 planTime 对应的 quantity
      };
    });
    loadingTable.value=false;
  }).catch(error => {
    loadingTable.value=false;
    console.error('获取生产计划详情失败:', error);
    ElMessage.error('获取生产计划详情失败');
  });
};

// 格式化日期为字符串
const formatDate = (date) => {
  return date ? `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}` : '';
};

// 更新按钮的点击事件
const updateProductionPlan = (state) => {
  // 将数据转换回原始结构
  if(!materialList.value || materialList.value.length===0){
    ElMessage.error("没有要排产的物料")
    return;
  }
  let isPlannedValid = true; // 添加一个标志变量

  const current = materialList.value.find((item) => item.workshop == null);
  if (current) { // 如果找到匹配的批号
    isPlannedValid = false; // 设置标志为 false
  }

  if (!isPlannedValid) {
    ElMessage.info("请选择生产车间");
    return; // 如果标志为 false，直接返回，不执行后续代码
  }
  const loading = ElLoading.service({
    lock: true,
    text: "加载中...",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)"
  });
  const productionPlanDetailList = materialList.value.map(material => {
    const grid = gridList.value.find(item=>item.gid===material.workshop);
    const planMaterialNumberList = Object.entries(material.scheduleQuantities).map(([dateString, quantity]) => {
      return {
        planTime: formatPlanTime(dateString),
        quantity
      };
    });
    const planSchedulingList = getSchedulingList(planMaterialNumberList,material.orderQuantity);
    return {
      id: material.id,
      schedulingQuantity:material.schedulingQuantity,
      materialCode: material.materialCode,
      materialName: material.materialName,
      orderQuantity: material.orderQuantity,
      gripId: material.workshop,
      gripName: grid?.gname,
      productPlanMaterialNumberList:planSchedulingList
    };
  });
  const planQuantity = productionPlanDetailList.reduce((total, item) => {
    return total + item.productPlanMaterialNumberList.reduce((subTotal, subItem) => subTotal + subItem.quantity, 0);
  }, 0);
  const params = {
    id: planId.value,
    planTime: productionPlan.value.planTime,
    remark: productionPlan.value.remark,
    materialNumber: materialList.value.length,
    planQuantity: planQuantity,
    completedQuantity: productionPlan.value.completedQuantity,
    productPlanMaterialList:productionPlanDetailList,
    state:state,
  };

  // 调用接口
  updateProductionPlanApi(params)
    .then(response => {
      ElMessage.success('更新成功!');
      router.push({name:"productionPlanList"}); // 返回列表页
    })
    .catch(error => {
      ElMessage.error('更新失败!');
      console.error('更新失败:', error);
    })
    .finally(()=>{
    loading.close();
  });
};

// 格式化计划时间
const formatPlanTime = (dateString) => {
  const [year, month, day] = dateString.split('-');
  return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
};

// 删除行
const deleteRow = (index) => {
  materialList.value.splice(index, 1);
};

//处理排产累计数量
const getSchedulingList = (list,total) => {
  const sortedData = [...list].sort((a, b) => new Date(a.planTime) - new Date(b.planTime));
  let cumulativeQuantity = Number(total);

  return sortedData.map(item => {
    if (item.quantity <= cumulativeQuantity){
      cumulativeQuantity -= item.quantity;
    } else {
      cumulativeQuantity = 0;
    }
    return { ...item, cumulativeQuantity };
  });
}

// 初始化
onMounted(() => {
  getGridList();
  getProductionPlanDetail();
});
</script>

<style scoped>
.production-scheduling {
  padding: 20px;
}

.quantity-input {
  margin-left: 10px;
}

.demo-form-inline {
  display: flex;
  justify-content: space-between;
}
</style>
